﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Diagnostics;
using System.Configuration;
using System.Collections;
using System.IO;
using VPIC_EDILib;
namespace VPIC_EDIGUI
{
    public class XMLProcess
    {
        ExactDataContext DS;
        Config itemConfig;
        public XMLProcess(Config _itemConfig)
        {
            DS = new ExactDataContext();
            itemConfig = _itemConfig;
            string ConnStrFormat ="Data Source={0};Initial Catalog={1};Integrated Security=True";
            DS.Connection.ConnectionString = String.Format(ConnStrFormat, itemConfig.ServerName, itemConfig.DBName);
        }
        public double GetExchangeRateCurrent(string CurrencyCode)
        {
            var query = from ExRate in DS.rates
                        where ExRate.source_currency == CurrencyCode && ExRate.date_l == DateTime.Now.Date
                        select ExRate;
            if (query.Count() > 0)
            {
                return query.First().rate_exchange;
            }
            else
            {
                return 1;
            }
        }

        public List<EDIEntity> GetListEDIEntitySOForecast(FileInfo fileEDI)
        {
            StreamReader ediReader = fileEDI.OpenText();
            List<EDIEntity> ListEDI = new List<EDIEntity>();
            int i = 0;
            while (ediReader.Peek() > 0)
            {
                if (i > 1)
                {
                    string line = ediReader.ReadLine();
                    string[] tokens = line.Split(new char[1] { ',' });
                    EDIEntity item = new EDIEntity();
                    item.Transaction_Set_Identifier_Code = tokens[0];
                    item.Transaction_Set_Control_Number = tokens[1];
                    item.Transaction_Set_Purpose_Code = tokens[2];
                    item.Release_Number = tokens[3];
                    item.Forecast_Type_Qualifier = tokens[4];
                    item.Forecast_Quantity_Qualifier = tokens[5];
                    item.Forecast_Horizon_Start_Date = tokens[6];
                    item.Forecast_Horizon_End_Date = tokens[7];
                    item.Forecast_Release_Date = tokens[8];
                    item.Entity_Identifier_Code_supplier = tokens[9];
                    item.Entity_Name_supplier = tokens[10];
                    item.Identification_Code_Qualifier_supplier = tokens[11];
                    item.Identification_Code_supplier = tokens[12];
                    item.Name_supplier_1 = tokens[13];
                    item.Name_supplier_2 = tokens[14];
                    item.Address_supplier_1 = tokens[15];
                    item.Address_supplier_2 = tokens[16];
                    item.City_supplier = tokens[17];
                    item.Province___State_supplier = tokens[18];
                    item.Zip_code_supplier = tokens[19];
                    item.Country_supplier = tokens[20];
                    item.Contact_Function_Code = tokens[21];
                    item.Contact_Name = tokens[22];
                    item.Communications_Number_Qualifier = tokens[23];
                    item.Communications_Number = tokens[24];
                    item.Entity_Identifier_Code_shipTo = tokens[25];
                    item.Entity_Name_shipTo = tokens[26];
                    item.Identification_Code_Qualifier_shipTo = tokens[27];
                    item.Identification_Code_shipTo = tokens[28];
                    item.Buyer_Part_Number_Qual = tokens[29];
                    item.Buyer_Part_Number = tokens[30];
                    item.Engineering_Change_Level_Number_Qual = tokens[31];
                    item.Engineering_Change_Level_Number = tokens[32];
                    item.Po_Number_Qual = tokens[33];
                    item.Po_Number = tokens[34];
                    item.Item = tokens[35];
                    item.Code_Qual_Description = tokens[36];
                    item.Product_Description = tokens[37];
                    item.Unit_Of_Measure = tokens[38];
                    item.Dock_Number_Qual = tokens[39];
                    item.Dock_Number = tokens[40];
                    item.Sales_Territory_Code_Qual = tokens[41];
                    item.Sales_Territory_Code = tokens[42];
                    item.Resource_Authorization_Code_Finished = tokens[43];
                    item.Authorized_Through_Date_Finished = tokens[44];
                    item.Authorized_Cumulative_Quantity_Finished = tokens[45];
                    item.Cumulative_Quantity_Start_Date_Finished = tokens[46];
                    item.Resource_Authorization_Code_Material = tokens[47];
                    item.Authorized_Through_Date_Material = tokens[48];
                    item.Authorized_Cumulative_Quantity_Material = tokens[49];
                    item.Cumulative_Quantity_Start_Date_Material = tokens[50];
                    item.Ship_Delivery_or_Calendar_Pattern_Code = tokens[51];
                    item.Ship_Delivery_Pattern_Time_Code = tokens[52];
                    item.Forecast_Quantity = tokens[53];
                    item.Forecast_Qualifier = tokens[54];
                    item.Forecast_Timing_Qualifier = tokens[55];
                    item.Forecast_Start_Date = tokens[56];
                    item.Forecast_End_Date = tokens[57];
                    item.Shipped_Quantity_Qualifier = tokens[58];
                    item.Shipped_Quantity = tokens[59];
                    item.Date_Time_Qualifier = tokens[60];
                    item.Date_Start = tokens[61];
                    item.Date_End = tokens[62];
                    item.Shippers_Identifying_Number_for_Shipment_Qual = tokens[63];
                    item.Shippers_Identifying_Number_for_Shipment = tokens[64];
                    item.Number_of_Line_item = tokens[65];
                    item.Quantity_summation = tokens[66];
                    item.nombre_de_record_in_the_transaction = tokens[67];
                    item.Control_number_transaction = tokens[68];
                    ListEDI.Add(item);

                }
                i++;


            }
            ediReader.Close();
            return ListEDI;
        }

        public List<EDIEntityShip> GetListEDIEntitySOShip(FileInfo fileEDI)
        {
            StreamReader ediReader = fileEDI.OpenText();
            List<EDIEntityShip> ListEDI = new List<EDIEntityShip>();
            int i = 0;
            while (ediReader.Peek() > 0)
            {
                if (i > 1)
                {
                    string line = ediReader.ReadLine();
                    string[] tokens = line.Split(new char[1] { ',' });
                    EDIEntityShip item = new EDIEntityShip();
                    item.Transaction_Set_Identifier_Code = tokens[0];
                    item.Transaction_Set_Control_Number = tokens[1];
                    item.Transaction_Set_Purpose_Code = tokens[2];
                    item.Reference_Identification_1 = tokens[3];
                    item.Issued_Date = tokens[4];
                    item.Schedule_Type_Qualifier = tokens[5];
                    item.Forecast_Horizon_Start_Date = tokens[6];
                    item.Forecast_Horizon_End_Date = tokens[7];
                    item.Release_Number = tokens[8];
                    item.Reference_Identification_2 = tokens[9];
                    item.Schedule_Quantity_Qualifier = tokens[10];
                    item.Most_recent_revision_Date_Time_Qualifier = tokens[11];
                    item.Most_recent_revision_Date = tokens[12];
                    item.Most_recent_revision_Time = tokens[13];
                    item.Entity_Identifier_Code_supplier = tokens[14];
                    item.Entity_Name_supplier = tokens[15];
                    item.Identification_Code_Qualifier_supplier = tokens[16];
                    item.Identification_Code_supplier = tokens[17];
                    item.Name_supplier_1 = tokens[18];
                    item.Name_supplier_2 = tokens[19];
                    item.Address_supplier_1 = tokens[20];
                    item.Address_supplier_2 = tokens[21];
                    item.City_supplier = tokens[22];
                    item.Province___State_supplier = tokens[23];
                    item.Zip_code_supplier = tokens[24];
                    item.Country_supplier = tokens[25];
                    item.Contact_Function_Code = tokens[26];
                    item.Contact_Name = tokens[27];
                    item.Communications_Number_Qualifier = tokens[28];
                    item.Communications_Number = tokens[29];
                    item.Entity_Identifier_Code_Ship_To = tokens[30];
                    item.Entity_Name_Ship_To = tokens[31];
                    item.Identification_Code_Qualifier_Ship_To = tokens[32];
                    item.Identification_Code_shipTo = tokens[33];
                    item.Buyer_Part_Number_Qual = tokens[34];
                    item.Buyer_Part_Number = tokens[35];
                    item.Engineering_Change_Level_Number_Qual = tokens[36];
                    item.Engineering_Change_Level_Number = tokens[37];
                    item.Po_Number_Qual = tokens[38];
                    item.Po_Number = tokens[39];
                    item.Item = tokens[40];
                    item.Code_Qual_Description = tokens[41];
                    item.Product_Description = tokens[42];
                    item.Unit_Of_Measure = tokens[43];
                    item.Dock_Number_Qual = tokens[44];
                    item.Dock_Number = tokens[45];
                    item.Sales_Territory_Code_Qual = tokens[46];
                    item.Sales_Territory_Code = tokens[47];
                    item.Ship_Delivery_Pattern_Code = tokens[48];
                    item.Ship_Delivery_Pattern_Time_Code = tokens[49];
                    item.Forecast_Quantity = tokens[50];
                    item.Forecast_Qualifier = tokens[51];
                    item.Forecast_Timing_Qualifier = tokens[52];
                    item.Forecast_Start_Date = tokens[53];
                    item.Forecast_End_Date = tokens[54];
                    item.Reference_Number_Qualifier = tokens[55];
                    item.Reference_Number = tokens[56];
                    item.Delivery_Ship_date_time_qualifier = tokens[57];
                    item.Delivery_Ship_date = tokens[58];
                    item.Delivery_Ship_time = tokens[59];
                    item.Just_In_Time_Quantity = tokens[60];
                    item.Time_JIT = tokens[61];
                    item.job_sequence_number_qualifier = tokens[62];
                    item.job_sequence_number = tokens[63];
                    item.Shipped_Quantity_Qualifier = tokens[64];
                    item.Shipped_Quantity = tokens[65];
                    item.Shipped_Date_Time_Qualifier = tokens[66];
                    item.Shipped_Start_Date = tokens[67];
                    item.Shipped_End_Date = tokens[68];
                    item.Shippers_Identifying_Number_for_Shipment_Qual = tokens[69];
                    item.Shippers_Identifying_Number_for_Shipment = tokens[70];
                    item.Number_of_Line_Items_LIN_segments = tokens[71];
                    item.Hash_Total_Sum_of_FST01 = tokens[72];
                    item.Number_of_Included_Segments = tokens[73];
                    item.Transaction_Set_Control_Number = tokens[74];

                    ListEDI.Add(item);

                }
                i++;


            }
            ediReader.Close();
            return ListEDI;
        }

        public void StartProcessImportInvoice(string filexml)
        {
            Process Proc = new Process();
            Proc.StartInfo.FileName = @"ASImport.exe";
            Proc.StartInfo.Arguments = "-r" + DS.Connection.DataSource + " -D" + DS.Connection.Database + " -u -~ I -URL" + filexml + " -Torders -OPT18 -Oauto";
            Proc.StartInfo.UseShellExecute = false;
            Proc.StartInfo.RedirectStandardError = true;
            Proc.StartInfo.RedirectStandardError = true;
            Proc.StartInfo.Verb = "runas";
            Proc.Start();

            Proc.WaitForExit();
            Proc.Close();
        }

        public string GetXMLSOForecast(List<EDIEntity> ListEDI)
        {
            string filename = itemConfig.ShareFolderXML + @"\Order_830_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            Hashtable hashData = new Hashtable();
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));

            //TAG ORDERS
            XElement elementOrders = new XElement("Orders");
        

            foreach (EDIEntity itemEDI in ListEDI)
            {

                string key = itemEDI.Transaction_Set_Identifier_Code + ";" + itemEDI.Forecast_Horizon_Start_Date + ";"
                            + itemEDI.Forecast_Horizon_End_Date + ";" + itemEDI.Forecast_Release_Date + ";" + itemEDI.Entity_Name_shipTo+";"+itemEDI.Transaction_Set_Purpose_Code;

                if (hashData.ContainsKey(key))
                {
                    List<EDIEntity> ListEDIItem = (List<EDIEntity>)hashData[key];

                    ListEDIItem.Add(itemEDI);
                    hashData[key] = ListEDIItem;
                }
                else
                {
                    List<EDIEntity> ListEDIItem = new List<EDIEntity>();
                    ListEDIItem.Add(itemEDI);
                    hashData[key] = ListEDIItem;
                }
            }
            foreach (object keyHeader in hashData.Keys)
            {

                string[] tokens = keyHeader.ToString().Split(new char[1] { ';' });
                EDIHeader itemEDI = new EDIHeader();
                itemEDI.Transaction_Set_Identifier_Code = tokens[0];
                itemEDI.Forecast_Horizon_Start_Date = tokens[1];
                itemEDI.Forecast_Horizon_End_Date = tokens[2];
                itemEDI.Forecast_Release_Date = tokens[3];
                itemEDI.Entity_Name_shipTo = tokens[4];
                itemEDI.Transaction_Set_Purpose_Code = tokens[5];

                // ORDER
                XElement elementOrder = new XElement("Order", new XAttribute("type", "V"), new XAttribute("partialdelivery", "1"), new XAttribute("code", "002"));
                XElement elementDescription = new XElement("Description", itemEDI.Transaction_Set_Identifier_Code+"-"+itemEDI.Transaction_Set_Purpose_Code);
                elementOrder.Add(elementDescription);
                XElement elementReference1 = new XElement("Reference1", itemEDI.Forecast_Horizon_Start_Date);
                elementOrder.Add(elementReference1);

                XElement elementReference2 = new XElement("Reference2", itemEDI.Forecast_Horizon_End_Date);
                elementOrder.Add(elementReference2);

                XElement elementReference3 = new XElement("Reference3", itemEDI.Forecast_Release_Date);
                elementOrder.Add(elementReference3);

                XElement elementYourRef = new XElement("YourRef", itemEDI.Entity_Name_shipTo);
                elementOrder.Add(elementYourRef);

                XElement elementOrderEntity = new XElement("Order");


                XElement elementOrderEntityWH = new XElement("Warehouse", new XAttribute("code", "VW05"));
                elementOrderEntity.Add(elementOrderEntityWH);

                XElement elementFreeFields = new XElement("FreeFields");
                XElement elementFreeTexts = new XElement("FreeTexts");
                XElement elementFreeText1 = new XElement("FreeText", new XAttribute("number", "1"));
                elementFreeTexts.Add(elementFreeText1);

                XElement elementFreeText2 = new XElement("FreeText", new XAttribute("number", "2"));
                elementFreeTexts.Add(elementFreeText2);

                XElement elementFreeText3 = new XElement("FreeText", new XAttribute("number", "3"));
                elementFreeTexts.Add(elementFreeText3);

                elementFreeFields.Add(elementFreeTexts);

                XElement elementFreeNumbers = new XElement("FreeNumbers");
                XElement elementFreeNumber1 = new XElement("FreeNumber", new XAttribute("number", "4"));
                elementFreeNumbers.Add(elementFreeNumber1);

                XElement elementFreeNumber2 = new XElement("FreeNumber", new XAttribute("number", "5"));
                elementFreeNumbers.Add(elementFreeNumber2);

                elementFreeFields.Add(elementFreeNumbers);
                elementOrderEntity.Add(elementFreeFields);
                elementOrder.Add(elementOrderEntity);


                XElement elementCurrency = new XElement("Currency", new XAttribute("code", "USD"));
                elementOrder.Add(elementCurrency);

                XElement elementRate = new XElement("Rate", this.GetExchangeRateCurrent("USD"));
                elementOrder.Add(elementRate);

                XElement elementResource = new XElement("Resource", new XAttribute("number", "4"));
                elementOrder.Add(elementResource);

                XElement elementOrderBy = new XElement("OrderedBy");
                XElement elementOrderByDebtor = new XElement("Debtor", new XAttribute("code", "4012"));
                elementOrderBy.Add(elementOrderByDebtor);

                XElement elementOrderByDate = new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"));
                elementOrderBy.Add(elementOrderByDate);


                elementOrder.Add(elementOrderBy);

                XElement elementDeliverTo = new XElement("DeliverTo");
                XElement elementDeliverToDebtor = new XElement("Debtor", new XAttribute("code", "4012"));
                elementDeliverTo.Add(elementDeliverToDebtor);
                elementOrder.Add(elementDeliverTo);



                XElement elementInvoiceTo = new XElement("InvoiceTo");
                XElement elementInvoiceToDebtor = new XElement("Debtor", new XAttribute("code", "4012"));
                elementInvoiceTo.Add(elementInvoiceToDebtor);


                elementOrder.Add(elementInvoiceTo);

                XElement elementWarehouse = new XElement("Warehouse", new XAttribute("code", "VW05"));
                elementOrder.Add(elementWarehouse);

                XElement elementPaymentCondition = new XElement("PaymentCondition", new XAttribute("code", "00"));
                elementOrder.Add(elementPaymentCondition);

                XElement elementDeliveryMethod = new XElement("DeliveryMethod", new XAttribute("code", "SH"));
                elementOrder.Add(elementDeliveryMethod);

                XElement elementCostCenter = new XElement("CostCenter", new XAttribute("code", "002"));
                elementOrder.Add(elementCostCenter);



                XElement elementHFreeFields = new XElement("FreeFields");
                XElement elementHFreeTexts = new XElement("FreeTexts");
                XElement elementHFreeText1 = new XElement("FreeText", new XAttribute("number", "1"));
                elementHFreeTexts.Add(elementHFreeText1);

                XElement elementHFreeText2 = new XElement("FreeText", new XAttribute("number", "2"));
                elementHFreeTexts.Add(elementHFreeText2);

                XElement elementHFreeText3 = new XElement("FreeText", new XAttribute("number", "3"));
                elementHFreeTexts.Add(elementHFreeText3);

                elementHFreeFields.Add(elementHFreeTexts);

                XElement elementHFreeNumbers = new XElement("FreeNumbers");
                XElement elementHFreeNumber1 = new XElement("FreeNumber", new XAttribute("number", "4"));
                elementHFreeNumbers.Add(elementHFreeNumber1);

                XElement elementHFreeNumber2 = new XElement("FreeNumber", new XAttribute("number", "5"));
                elementHFreeNumbers.Add(elementHFreeNumber2);

                elementHFreeFields.Add(elementHFreeNumbers);
                elementOrder.Add(elementHFreeFields);

                List<EDIEntity> ListEDIEntity = (List<EDIEntity>)hashData[keyHeader];

                foreach (EDIEntity itemEDIEntity in ListEDIEntity)
                {
                    XElement elementOrderLine = new XElement("OrderLine");
                    string itemcode ="";
                    if(itemEDIEntity.Buyer_Part_Number.Length ==9)
                    {
                        itemcode = "FN-"+itemEDIEntity.Buyer_Part_Number.Substring(0,3)+" "
                                + itemEDIEntity.Buyer_Part_Number.Substring(3,3) +" " 
                                + itemEDIEntity.Buyer_Part_Number.Substring(6,3);
                    }
                    XElement elementItemCode = new XElement("Item", new XAttribute("code", itemcode));
                    elementOrderLine.Add(elementItemCode);

                    XElement elementPriceList = new XElement("PriceList", new XAttribute("code", "NN-005"));
                    elementOrderLine.Add(elementPriceList);

                    XElement elementQuantity = new XElement("Quantity", itemEDIEntity.Forecast_Quantity);
                    elementOrderLine.Add(elementQuantity);

                    XElement elementUnit = new XElement("Unit", new XAttribute("unit", "PCS"));
                    elementOrderLine.Add(elementUnit);

                    XElement elementPrice = new XElement("Price");
                    XElement elementCurrencyPrice = new XElement("Currency", new XAttribute("code", "USD"));
                    elementPrice.Add(elementCurrencyPrice);
                    //XElement elementValuePrice = new XElement("Value");
                    //elementPrice.Add(elementValuePrice);
                    XElement elementVATPrice = new XElement("VAT",new XAttribute("code","0"));
                    elementPrice.Add(elementVATPrice);

                    elementOrderLine.Add(elementPrice);

                    XElement elementDelivery = new XElement("Delivery");
                    XElement elementDeliveryDate = new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"));
                    elementDelivery.Add(elementDeliveryDate);
                    elementOrderLine.Add(elementDelivery);

                    XElement elementWHOrderLine = new XElement("Warehouse", new XAttribute("code", "VW05"));
                    elementOrderLine.Add(elementWHOrderLine);

                    XElement elementProject = new XElement("Project", new XAttribute("code", ""));
                    XElement elementProjectAccount = new XElement("Account", new XAttribute("code", "4012"));
                    elementProject.Add(elementProjectAccount);
                    elementOrderLine.Add(elementProject);

                    XElement elementInstruction = new XElement("Instruction", itemEDIEntity.Engineering_Change_Level_Number + "-" + itemEDIEntity.Po_Number);
                    elementOrderLine.Add(elementInstruction);

                    elementOrder.Add(elementOrderLine);




                }
                elementOrders.Add(elementOrder);
            }

            elementRoot.Add(elementOrders);
            doc.Add(elementRoot);
            doc.Save(filename);
            return filename;
        }

        public string GetXMLSOShippingSchedules(List<EDIEntityShip> ListEDI)
        {
            string filename = itemConfig.ShareFolderXML + @"\Order_862_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            Hashtable hashData = new Hashtable();
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));

            //TAG ORDERS
            XElement elementOrders = new XElement("Orders");


            foreach (EDIEntityShip itemEDI in ListEDI)
            {

                string key = itemEDI.Transaction_Set_Identifier_Code + ";" + itemEDI.Forecast_Horizon_Start_Date + ";"
                            + itemEDI.Forecast_Horizon_End_Date + ";" + itemEDI.Most_recent_revision_Date + ";" + itemEDI.Entity_Name_Ship_To+";"+itemEDI.Issued_Date+";"+
                            itemEDI.Transaction_Set_Purpose_Code;

                if (hashData.ContainsKey(key))
                {
                    List<EDIEntityShip> ListEDIItem = (List<EDIEntityShip>)hashData[key];

                    ListEDIItem.Add(itemEDI);
                    hashData[key] = ListEDIItem;
                }
                else
                {
                    List<EDIEntityShip> ListEDIItem = new List<EDIEntityShip>();
                    ListEDIItem.Add(itemEDI);
                    hashData[key] = ListEDIItem;
                }
            }
            foreach (object keyHeader in hashData.Keys)
            {

                string[] tokens = keyHeader.ToString().Split(new char[1] { ';' });
                EDIHeaderShip itemEDI = new EDIHeaderShip();
                itemEDI.Transaction_Set_Identifier_Code = tokens[0];
                itemEDI.Forecast_Horizon_Start_Date = tokens[1];
                itemEDI.Forecast_Horizon_End_Date = tokens[2];
                itemEDI.Most_recent_revision_Date = tokens[3];
                itemEDI.Entity_Name_shipTo = tokens[4];
                itemEDI.Issued_Date = tokens[5];
                itemEDI.Transaction_Set_Purpose_Code = tokens[6];

                // ORDER
                XElement elementOrder = new XElement("Order", new XAttribute("type", "V"), new XAttribute("partialdelivery", "1"), new XAttribute("code", "002"));
                XElement elementDescription = new XElement("Description", itemEDI.Transaction_Set_Identifier_Code+"-"+itemEDI.Transaction_Set_Purpose_Code);
                elementOrder.Add(elementDescription);
                XElement elementReference1 = new XElement("Reference1", itemEDI.Forecast_Horizon_Start_Date);
                elementOrder.Add(elementReference1);

                XElement elementReference2 = new XElement("Reference2", itemEDI.Forecast_Horizon_End_Date);
                elementOrder.Add(elementReference2);

                XElement elementReference3 = new XElement("Reference3", itemEDI.Most_recent_revision_Date + itemEDI.Issued_Date);
                elementOrder.Add(elementReference3);

                XElement elementYourRef = new XElement("YourRef", itemEDI.Entity_Name_shipTo);
                elementOrder.Add(elementYourRef);

                XElement elementOrderEntity = new XElement("Order");


                XElement elementOrderEntityWH = new XElement("Warehouse", new XAttribute("code", "VW05"));
                elementOrderEntity.Add(elementOrderEntityWH);

                XElement elementFreeFields = new XElement("FreeFields");
                XElement elementFreeTexts = new XElement("FreeTexts");
                XElement elementFreeText1 = new XElement("FreeText", new XAttribute("number", "1"));
                elementFreeTexts.Add(elementFreeText1);

                XElement elementFreeText2 = new XElement("FreeText", new XAttribute("number", "2"));
                elementFreeTexts.Add(elementFreeText2);

                XElement elementFreeText3 = new XElement("FreeText", new XAttribute("number", "3"));
                elementFreeTexts.Add(elementFreeText3);

                elementFreeFields.Add(elementFreeTexts);

                XElement elementFreeNumbers = new XElement("FreeNumbers");
                XElement elementFreeNumber1 = new XElement("FreeNumber", new XAttribute("number", "4"));
                elementFreeNumbers.Add(elementFreeNumber1);

                XElement elementFreeNumber2 = new XElement("FreeNumber", new XAttribute("number", "5"));
                elementFreeNumbers.Add(elementFreeNumber2);

                elementFreeFields.Add(elementFreeNumbers);
                elementOrderEntity.Add(elementFreeFields);
                elementOrder.Add(elementOrderEntity);


                XElement elementCurrency = new XElement("Currency", new XAttribute("code", "USD"));
                elementOrder.Add(elementCurrency);

                XElement elementRate = new XElement("Rate", this.GetExchangeRateCurrent("USD"));
                elementOrder.Add(elementRate);

                XElement elementResource = new XElement("Resource", new XAttribute("number", "4"));
                elementOrder.Add(elementResource);

                XElement elementOrderBy = new XElement("OrderedBy");
                XElement elementOrderByDebtor = new XElement("Debtor", new XAttribute("code", "4012"));
                elementOrderBy.Add(elementOrderByDebtor);

                XElement elementOrderByDate = new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"));
                elementOrderBy.Add(elementOrderByDate);
                elementOrder.Add(elementOrderBy);


                XElement elementDeliverTo = new XElement("DeliverTo");
                XElement elementDeliverToDebtor = new XElement("Debtor", new XAttribute("code", "4012"));
                elementDeliverTo.Add(elementDeliverToDebtor);
                elementOrder.Add(elementDeliverTo);



                XElement elementInvoiceTo = new XElement("InvoiceTo");
                XElement elementInvoiceToDebtor = new XElement("Debtor", new XAttribute("code", "4012"));
                elementInvoiceTo.Add(elementInvoiceToDebtor);
                elementOrder.Add(elementInvoiceTo);

                XElement elementWarehouse = new XElement("Warehouse", new XAttribute("code", "VW05"));
                elementOrder.Add(elementWarehouse);

                XElement elementPaymentCondition = new XElement("PaymentCondition", new XAttribute("code", "00"));
                elementOrder.Add(elementPaymentCondition);

                XElement elementDeliveryMethod = new XElement("DeliveryMethod", new XAttribute("code", "SH"));
                elementOrder.Add(elementDeliveryMethod);

                XElement elementCostCenter = new XElement("CostCenter", new XAttribute("code", "002"));
                elementOrder.Add(elementCostCenter);



                XElement elementHFreeFields = new XElement("FreeFields");
                XElement elementHFreeTexts = new XElement("FreeTexts");
                XElement elementHFreeText1 = new XElement("FreeText", new XAttribute("number", "1"));
                elementHFreeTexts.Add(elementHFreeText1);

                XElement elementHFreeText2 = new XElement("FreeText", new XAttribute("number", "2"));
                elementHFreeTexts.Add(elementHFreeText2);

                XElement elementHFreeText3 = new XElement("FreeText", new XAttribute("number", "3"));
                elementHFreeTexts.Add(elementHFreeText3);

                elementHFreeFields.Add(elementHFreeTexts);

                XElement elementHFreeNumbers = new XElement("FreeNumbers");
                XElement elementHFreeNumber1 = new XElement("FreeNumber", new XAttribute("number", "4"));
                elementHFreeNumbers.Add(elementHFreeNumber1);

                XElement elementHFreeNumber2 = new XElement("FreeNumber", new XAttribute("number", "5"));
                elementHFreeNumbers.Add(elementHFreeNumber2);

                elementHFreeFields.Add(elementHFreeNumbers);
                elementOrder.Add(elementHFreeFields);

                List<EDIEntityShip> ListEDIEntity = (List<EDIEntityShip>)hashData[keyHeader];

                foreach (EDIEntityShip itemEDIEntity in ListEDIEntity)
                {
                    XElement elementOrderLine = new XElement("OrderLine");
                    string itemcode = "";
                    if (itemEDIEntity.Buyer_Part_Number.Length == 9)
                    {
                        itemcode = "FN-" + itemEDIEntity.Buyer_Part_Number.Substring(0, 3) + " "
                                + itemEDIEntity.Buyer_Part_Number.Substring(3, 3) + " "
                                + itemEDIEntity.Buyer_Part_Number.Substring(6, 3);
                    }
                    XElement elementItemCode = new XElement("Item", new XAttribute("code", itemcode));
                    elementOrderLine.Add(elementItemCode);

                    XElement elementPriceList = new XElement("PriceList", new XAttribute("code", "NN-005"));
                    elementOrderLine.Add(elementPriceList);

                    XElement elementQuantity = new XElement("Quantity", itemEDIEntity.Forecast_Quantity);
                    elementOrderLine.Add(elementQuantity);

                    XElement elementUnit = new XElement("Unit", new XAttribute("unit", "PCS"));
                    elementOrderLine.Add(elementUnit);

                    XElement elementPrice = new XElement("Price");
                    XElement elementCurrencyPrice = new XElement("Currency", new XAttribute("code", "USD"));
                    elementPrice.Add(elementCurrencyPrice);
                    //XElement elementValuePrice = new XElement("Value");
                    //elementPrice.Add(elementValuePrice);
                    XElement elementVATPrice = new XElement("VAT", new XAttribute("code", "0"));
                    elementPrice.Add(elementVATPrice);

                    elementOrderLine.Add(elementPrice);

                    XElement elementDelivery = new XElement("Delivery");
                    XElement elementDeliveryDate = new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"));
                    elementDelivery.Add(elementDeliveryDate);
                    elementOrderLine.Add(elementDelivery);

                    XElement elementWHOrderLine = new XElement("Warehouse", new XAttribute("code", "VW05"));
                    elementOrderLine.Add(elementWHOrderLine);

                    XElement elementProject = new XElement("Project", new XAttribute("code", ""));
                    XElement elementProjectAccount = new XElement("Account", new XAttribute("code", "4012"));
                    elementProject.Add(elementProjectAccount);
                    elementOrderLine.Add(elementProject);

                    XElement elementInstruction = new XElement("Instruction", itemEDIEntity.Engineering_Change_Level_Number + "-" + itemEDIEntity.Po_Number);
                    elementOrderLine.Add(elementInstruction);

                    elementOrder.Add(elementOrderLine);




                }
                elementOrders.Add(elementOrder);
            }

            elementRoot.Add(elementOrders);
            doc.Add(elementRoot);
            doc.Save(filename);
            return filename;
        }

    }
}
